﻿using RFIDSystem.IServices;
using RFIDSystem.Model.Models;
using RFIDSystem.Model.ViewModels;
using RFIDSystem.Services.BASE;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RFIDSystem.Services
{
    public class InspectionRecordServices : BaseServices<InspectionRecord>, IInspectionRecordServices
    {
        private readonly IRfidServices _rfidServices;

        public InspectionRecordServices(IRfidServices rfidServices)
        {
            _rfidServices = rfidServices;
        }

        public async Task<bool> DelInspectionRecord(string id)
        {
            var bloglist = await base.DeleteById(id);

            return true;
        }

        public async Task<List<InspectionRecordViewModel>> GetInspectionRecords(DateTime dateTime)
        {
            List<InspectionRecordViewModel> rs = new List<InspectionRecordViewModel>();
            var irs = await _rfidServices.Query(q => q.ParentId != 0);

            
            var irds = await base.QueryMuch<InspectionRecord,RFID, InspectionRecordViewModel>((ir,r)=>new object[] { JoinType.Left, ir.RFIDName == r.Name }, (ir, r) => new InspectionRecordViewModel { Id=ir.Id.SelectAll(),lng=r.lng,Lat=r.Lat} , (ir, r) => ir.CreateTime.ToString("yyyy-MM-dd")==dateTime.ToString("yyyy-MM-dd"));
            foreach (var ir in irs)
            {
                InspectionRecordViewModel r = new InspectionRecordViewModel();
                r.Id = ir.Id;
               
                r.ActivatorName = ir.Name;
                List<InspectionRecordChildren> irc=new List<InspectionRecordChildren>();
                irc=irds.Where(q=>q.ActivatorName==ir.Name).Select(q=>new InspectionRecordChildren { RFIDName=q.RFIDName, CreateTime=q.CreateTime, Lat=q.Lat, lng=q.lng, position=q.position}).ToList();
                if (irc.Count() > 0) {
                    irc.ForEach(q =>{ q.position[0] = q.Lat; q.position[1] = q.lng; });

                    r.childrens.AddRange(irc);
                }
                rs.Add(r);
            }
 

            return rs;
        }

       
    }
}
